/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

/**
 *
 * @author eisental
 */
public class SpyObject extends ShellObject {

    public SpyObject(DriveShell shell) { super("spy", "spies", "spy", shell); }

    @Override
    public boolean isActionSupported(Action action) {
        return (action!=Action.set);
    }

    @Override
    public void make(String command) throws IllegalArgumentException {
        // make spy on spytype:spycriteria
        command = command.trim();
        if (!command.startsWith("on ")) throw new IllegalArgumentException("Invalid syntax (should be: make spy on <type>:<criteria> )");
            
        String spycommand = command.substring(3).trim();

        Spy spy = Spy.createSpy(spycommand, shell.getActiveChain(), out);
        shell.getSpies().put(spy.getName(), spy);
        out.println("Added spy " + spy.getName() + " on chain " + spy.getChain().getName());

    }

    @Override
    public void remove(String command) throws IllegalArgumentException {
        Spy spy = shell.getSpies().get(command);
        if (spy==null) throw new IllegalArgumentException("Unknown spy '" + command + "'");
        spy.destroy();
        shell.getSpies().remove(command);
        out.println("Spy " + command + " is removed.");
    }

    @Override
    public void set(String command) throws IllegalArgumentException {
        throw new UnsupportedOperationException("Not supported.");
    }

    @Override
    public void list() throws IllegalArgumentException {
        if (!shell.getSpies().isEmpty()) {
            for (String spyName : shell.getSpies().keySet()) {
                Spy spy = shell.getSpies().get(spyName);
                out.println("   " + spyName + " " + spy + "\n      " + spy.report());
            }
        } else out.println("  There currently no spies attached.");
    }

    @Override
    public void inspect(String command) throws IllegalArgumentException {
        Spy spy = shell.getSpies().get(command);
        if (spy==null) throw new IllegalArgumentException("Unknown spy '" + command + "'");
        out.println("   " + command + " " + spy + "\n      " + spy.report());
    }

}
